package com.ca.ridersclubapplication.util;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.request.FileRequester;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class PaperUtils {

    public static String parsePaperForText(String paperContext) {

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            byte[] buffer = paperContext.getBytes(StandardCharsets.UTF_8);
            ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
            Document document = builder.parse(bis);

            Element paperElement = document.getDocumentElement();
            NodeList nodes = paperElement.getChildNodes();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < nodes.getLength(); i++) {
                Node pn = nodes.item(i);
                NodeList pnNodes = pn.getChildNodes();
                for (int j = 0; j < pnNodes.getLength(); j++) {
                    Node node = pnNodes.item(j);
                    String nodeName = node.getNodeName();
                    if ("text".equals(nodeName)) {
                        sb.append(node.getTextContent()).append(" ");
                    }
                }
            }

            return sb.toString();
        }
        catch (Exception e) {
            return "";
        }
    }

    public static String[] parsePaperImageUrlArray(String paperContext) {

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            byte[] buffer = paperContext.getBytes(StandardCharsets.UTF_8);
            ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
            Document document = builder.parse(bis);

            Element paperElement = document.getDocumentElement();
            NodeList nodes = paperElement.getChildNodes();

            List<String> imageNetPathList = new ArrayList<>();
            for (int i = 0; i < nodes.getLength(); i++) {
                Node pn = nodes.item(i);
                NodeList pnNodes = pn.getChildNodes();
                for (int j = 0; j < pnNodes.getLength(); j++) {
                    Node node = pnNodes.item(j);
                    String nodeName = node.getNodeName();
                    if ("image".equals(nodeName)) {
                        String path = node.getTextContent().replaceAll("&amp;", "&");
                        imageNetPathList.add(path);
                    }
                }
            }

            String[] array = new String[imageNetPathList.size()];
            for (int i = 0; i < array.length; i++) {
                array[i] = imageNetPathList.get(i);
            }
            return array;
        }
        catch (Exception e) {
            return new String[0];
        }
    }

    public static Map<String, List<String>> parseImage(String content) {

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            byte[] buffer = content.getBytes(StandardCharsets.UTF_8);
            ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
            Document document = builder.parse(bis);

            Element paperElement = document.getDocumentElement();
            NodeList nodes = paperElement.getChildNodes();

            Map<String, List<String>> map = new HashMap<>();

            for (int i = 0; i < nodes.getLength(); i++) {

                Node pn = nodes.item(i);
                NodeList appearanceNodes = pn.getChildNodes();

                String pnName = pn.getNodeName();
                List<String> list = new ArrayList<>();
                for (int j = 0; j < appearanceNodes.getLength(); j++) {
                    Node node = appearanceNodes.item(j);
                    if (node != null) {
                        String nodeName = node.getNodeName();
                        if ("image".equals(nodeName)) {
                            list.add(node.getTextContent());
                        }
                    }
                }

                map.put(pnName, list);
            }

            return map;
        }
        catch (Exception e) {
            Log.e("PaperUtil", "parsePaper 失败：" + e.getMessage());
            return new HashMap<>();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static Map<String, String> parsePaper(String content) {

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            byte[] buffer = content.getBytes(StandardCharsets.UTF_8);
            ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
            Document document = builder.parse(bis);

            Element paperElement = document.getDocumentElement();
            NodeList nodes = paperElement.getChildNodes();

            Map<String, String> map = new HashMap<>();

            for (int i = 0; i < nodes.getLength(); i++) {
                Node pn = nodes.item(i);
                NodeList appearanceNodes = pn.getChildNodes();

                String pnName = pn.getNodeName();
                for (int j = 0; j < appearanceNodes.getLength(); j++) {
                    Node node = appearanceNodes.item(j);
                    if (node != null) {
                        String nodeName = node.getNodeName();
                        if ("text".equals(nodeName)) {
                            map.put(pnName, node.getTextContent());
                            break;
                        }
                    }
                }
            }

            String s;
            s = map.get("appearance");
            if (s == null || s.trim().isEmpty()) {
                map.put("appearance", "无");
            }
            s = map.get("performance");
            if (s == null || s.trim().isEmpty()) {
                map.put("performance", "无");
            }
            s = map.get("energy");
            if (s == null || s.trim().isEmpty()) {
                map.put("energy", "无");
            }
            s = map.get("more");
            if (s == null || s.trim().isEmpty()) {
                map.put("more", "无");
            }

            return map;
        }
        catch (Exception e) {
            Log.e("PaperUtil", "parsePaper 失败：" + e.getMessage());
            return new HashMap<>();
        }
    }

    public static String createContent(
            Long accountId,
            String appearance, List<String> appearanceUUIDList,
            String performance, List<String> performanceUUIDList,
            String energy, List<String> energyImageUUIDList,
            String more, List<String> moreImageUUIDList) {

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            document.setXmlStandalone(true);

            //  根节点
            Element paper = document.createElement("paper");

            //  外观
            Element appearanceElement = document.createElement("appearance");
            Element ate = document.createElement("text");
            ate.setTextContent(appearance);
            appearanceElement.appendChild(ate);
            for (String url : appearanceUUIDList) {
                Element ie = document.createElement("image");
                ie.setTextContent(FileRequester.PAPER_IMAGE_BASE_URL + "?id=" + accountId + "&uuid=" + url);
                appearanceElement.appendChild(ie);
            }
            paper.appendChild(appearanceElement);

            //  性能
            Element performanceElement = document.createElement("performance");
            Element pte = document.createElement("text");
            pte.setTextContent(performance);
            performanceElement.appendChild(pte);
            for (String url : performanceUUIDList) {
                Element ie = document.createElement("image");
                ie.setTextContent(FileRequester.PAPER_IMAGE_BASE_URL + "?id=" + accountId + "&uuid=" + url);
                performanceElement.appendChild(ie);
            }
            paper.appendChild(performanceElement);

            //  能耗
            Element energyElement = document.createElement("energy");
            Element ete = document.createElement("text");
            ete.setTextContent(energy);
            energyElement.appendChild(ete);
            for (String url : energyImageUUIDList) {
                Element ie = document.createElement("image");
                ie.setTextContent(FileRequester.PAPER_IMAGE_BASE_URL + "?id=" + accountId + "&uuid=" + url);
                energyElement.appendChild(ie);
            }
            paper.appendChild(energyElement);

            //  其他
            Element moreElement = document.createElement("more");
            Element mte = document.createElement("text");
            mte.setTextContent(more);
            moreElement.appendChild(mte);
            for (String url : moreImageUUIDList) {
                Element ie = document.createElement("image");
                ie.setTextContent(FileRequester.PAPER_IMAGE_BASE_URL + "?id=" + accountId + "&uuid=" + url);
                moreElement.appendChild(ie);
            }
            paper.appendChild(moreElement);

            //  完成最后的封装
            document.appendChild(paper);

            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer transformer = tff.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            StreamResult result = new StreamResult(bos);
            transformer.transform(new DOMSource(document), result);

            //  返回封装完成的XML字符串
            return bos.toString();
        }
        catch (Exception e) {
            Log.e("Paper Utils", "createContent 失败：" + e.getMessage());
            return "";
        }
    }
}
